<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 督办事项新增编辑查看，承办事项查看 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel != 0 ? rules : {}"
    >
      <a-spin :spinning="loading">
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="项目基本信息" />
          <!--@popupScroll="(name, e) => (popupScrollArr.includes(name) ? handleScroll(name, e) : null)"-->
          <custom-form
            :form-list="formList"
            :form="form"
            :edit-model="editModel == 0 ? 'V' : ''"
          />
        </a-card>
        <!--反馈结果 待提交||结果未反馈均不显示-->
        <a-card
          v-if="editModel == 0 && form.overseeStatus != 'DRAFT' && form.overseeStatus != 'NO_FEEDBACK'"
          :bordered="false"
        >
          <title-name title="反馈结果" />
          <custom-form
            :form-list="resultList"
            :form="form"
            :edit-model="editModel == 0 ? 'V' : ''"
          >
            <!-- 附件上传 -->
            <template #feedbackList>
              <file-link :file-list="form.feedbackVO ? form.feedbackVO.feedbackFile : []" />
            </template>
          </custom-form>
        </a-card>
        <!--延期申请-->
        <a-card
          v-if="editModel == 0 && form.delayApplyVO"
          :bordered="false"
        >
          <title-name title="延期申请" />
          <custom-form
            :form-list="delayApplyList"
            :form="form"
            :edit-model="editModel == 0 ? 'V' : ''"
          >
            <!-- 附件上传 -->
            <template #delayApplyfileList>
              <file-link :file-list="form.delayApplyVO ? form.delayApplyVO.delayApplyFile : []" />
            </template>
          </custom-form>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top">
        <a-button
          v-if="editModel != 0"
          :loading="loading[0]"
          type="primary"
          class="button_right"
          @click="handleSubmit(1)"
        >
          保存草稿
        </a-button>
        <a-button
          v-if="editModel != 0"
          :loading="loading[1]"
          type="primary"
          class="button_right"
          @click="handleSubmit(2)"
        >
          提交
        </a-button>
        <a-button
          type="primary"
          @click="handleActiveClose"
        >
          关闭
        </a-button>
      </div>
    </a-form-model>
  </base-breadcrumb>
</template>

<script>
import { create, update, detail } from '@/api/office/supervise' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import SelectSupevise from '@/components/Select/SelectSupevise'
import SelectUndertaking from '@/components/Select/SelectUndertaking'
// import Selector from '@/components/Select/Selector'
import { getEmployeesList } from '@/api/commons.js'
import { getLabels } from '@/api/office/supervise.js'
import { getEmployees } from '@/api/businessAffairs/revenueAndCost'
import moment from 'moment'

export default {
  extends: new BaseEditPage(),
  data() {
    return {
      loading: false, // 加载控件
      editModel: this.$route.query.editModel, // 操作状态:0 查看;1 编辑;2 新增
      form: {
        feedbackVO: {
          feedbackFile: []
        },
        launchUnitId: JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.id,
        creatorId: JSON.parse(sessionStorage.getItem('ycloud-user_info')).id,
        launchDeptId: JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.deptId
      }, // 表单
      rules: {
        lanuchUnitId: [{ required: true, whitespace: true, message: '督办发起单位未获取', trigger: 'change' }],
        launchDeptId: [{ required: true, message: '督办发起部门未获取', trigger: 'change' }],
        creatorId: [{ required: true, message: '经办人未获取', trigger: 'change' }],
        deptPrincipal: [{ required: true, message: '请选择督办部门负责人', trigger: 'change' }],
        matterTypeId: [{ required: true, message: '请选择督办事项分类', trigger: 'change' }],
        planCompleteTime: [{ required: true, message: '请选择计划完成时间 ', trigger: 'change' }],
        matter: [{ required: true, message: '请输入督办事项 ', trigger: 'change' }],
        contentAbstract: [{ required: true, message: '请输入内容摘要及办理要求', trigger: 'change' }],
        princi: [{ required: true, message: '请选择承办领导/部门负责人', trigger: 'blur' }]
      }, // 校验规则
      init: false, // 初始化控件
      formCode: '', // 形式选中项code
      deptPrincipalData: [], //督办部门负责人数据
      matterTypeArr: [], //督办事项分类数据
      principalJobsData: [], //承办领导/部门负责人
      deptPageNumber: 1, //督办部门负责人列表当前页
      deptTotalPages: 1, //督办部门负责人列表总页
      deptNameLike: '', //督办部门负责人模糊查询
      popupScrollArr: ['deptPrincipalId', 'princi'],
      princiPageNumber: 1, //承办领导/部门负责人当前页
      princiTotalPages: 1 //承办领导/部门负责人总页
    }
  },
  computed: {
    resultList() {
      return [
        {
          keyName: 'undertakeResult',
          viewName: 'feedbackVO',
          type: 'BaseTextarea',
          label: '承办结果',
          disabled: true,
          customRender(i) {
            if (i) {
              return i.undertakeResult
            }
          },
          span: 24
        },
        {
          keyName: 'feedbackTime',
          viewName: 'feedbackVO',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          label: '实际反馈时间',
          disabled: true,
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          },
          customRender(i) {
            if (i) {
              return i.feedbackTime
            }
          }
        },
        {
          slot: true,
          keyName: 'feedbackList',
          label: '附件',
          span: 24
        }
      ]
    },
    delayApplyList() {
      return [
        {
          keyName: 'delayReason',
          viewName: 'delayApplyVO',
          type: 'BaseTextarea',
          label: '延期申请原因',
          disabled: true,
          customRender(i) {
            if (i) {
              return i.delayReason
            }
          },
          span: 24
        },
        {
          keyName: 'delayCompleteTime',
          viewName: 'delayApplyVO',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          label: '延期后完成时间',
          disabled: true,
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          },
          customRender(i) {
            if (i) {
              return i.delayCompleteTime
            }
          }
        },
        {
          slot: true,
          keyName: 'delayApplyfileList',
          label: '附件',
          span: 24
        }
      ]
    },
    formList() {
      return [
        {
          keyName: 'launchUnitId',
          viewName: 'launchUnitName',
          type: 'a-select',
          disabled: true,
          label: '督办发起单位',
          data: [
            {
              value: JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.id,
              label: JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.name
            }
          ]
        },
        {
          keyName: 'launchDeptId',
          viewName: 'launchDeptName',
          type: 'a-select',
          disabled: true,
          label: '督办发起部门',
          data: [
            {
              value: JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.deptId,
              label: JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.deptName
            }
          ]
        },
        {
          keyName: 'creatorId',
          viewName: 'creatorName',
          label: '经办人',
          type: 'a-select',
          disabled: true,
          data: [
            {
              value: JSON.parse(sessionStorage.getItem('ycloud-user_info')).id,
              label: JSON.parse(sessionStorage.getItem('ycloud-user_info')).name
            }
          ]
        },
        {
          keyName: 'deptPrincipal',
          viewName: 'deptPrincipalName',
          label: '督办部门负责人',
          type: SelectSupevise,
          placeholder: '请选择督办部门负责人',
          attrs: {
            labelInValue: true
          },
          ellipsis: true
        },
        {
          keyName: 'matterTypeId',
          viewName: 'matterType',
          label: '督办事项分类',
          type: 'a-select',
          data: this.matterTypeArr,
          replaceFields: {
            value: 'id', // 默认为value
            label: 'name' // 默认为label
          },
          customRender(i) {
            if (i) {
              return i.name
            }
          }
        },
        {
          keyName: 'planCompleteTime',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          label: '计划完成时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD',
            disabledDate: (current) => {
              return current && current < moment().endOf('day')
            }
          }
        },
        {
          keyName: 'matter',
          type: 'BaseTextarea',
          label: '督办事项',
          span: 24
        },
        {
          keyName: 'contentAbstract',
          type: 'BaseTextarea',
          label: '内容摘要及办理要求',
          span: 24
        },
        {
          keyName: 'princi',
          viewName: 'principalJobs',
          label: '承办领导/部门负责人',
          type: SelectUndertaking,
          placeholder: '请选择承办领导/部门负责人或输入名称搜索',
          span: 24
          // type: 'a-select',
          // typeGroup: 'a-select-opt-group',
          // data: this.principalJobsData,
          // optGroup:true,
          // attrs:{
          //   labelInValue:true,
          //   optionFilterProp:'children',
          //   filterOption(input, option) {
          //     let children = option.componentOptions.children[0].children
          //     let text = children ? children[1].text : option.componentOptions.children[0].text
          //     return text.toLowerCase().indexOf(input.toLowerCase()) >= 0
          //   },
          //   showSearch:true,
          // },
          // replaceFields: {
          //   label: 'name', // 父级label
          //   childValue: 'userId', // 子级value
          //   childLabel: 'name', // 子级label
          //   childOpt: 'postParentList', //其他
          // },
          // customRender(i,j){
          //   if(i && j){
          //     if(i.userId && j[0].id){
          //       return i.userId+'/'+j[0].id
          //     }
          //   }else if(i && !j){
          //     return i
          //   }
          // },
          // customRenderLabel(i,j){
          //   if(i && j){
          //     if(i.userId && j[0].id){
          //       return i.name+': '+j[0].name
          //     }
          //   }
          // },
        }
      ]
    }
  },
  watch: {},
  mounted() {
    let title = this.$route.meta.title
    if (title.indexOf('督办') >= 0) {
      this.$route.meta.title = ['督办事项查看', '督办事项编辑', '督办事项新增'][this.editModel]
    } else if (title.indexOf('承办') >= 0) {
      this.$route.meta.title = ['承办事项查看', '承办事项编辑', '承办事项新增'][this.editModel]
    }

    /**
     * 不为添加时请求详情
     * */
    if (this.editModel != 2) {
      this.loading = true
      detail({ id: this.id })
        .then((res) => {
          this.loading = false
          this.form = res.data
          this.form.matterTypeId = res.data.matterType.id
          this.form.princi = {
            key: res.data.principal + '/' + res.data.principalJobsId,
            label: res.data.principalJobs
          }
          this.form.deptPrincipal = {
            key: res.data.deptPrincipalId,
            label: res.data.deptPrincipalName
          }
          this.$nextTick(() => {
            this.init = true
          })
        })
        .catch(() => {
          this.loading = false
        })
    } else {
      this.$nextTick(() => {
        this.init = true
      })
    }
    /**
     * 分类
     **/
    getLabels({ query: { type: '6' } })
      .then((res) => {
        this.matterTypeArr = res.data
      })
      .catch(() => {})
  },
  methods: {
    /**
     * 校验表单
     */
    handleSubmit(val) {
      if (val == '2') {
        // 提交表单
        // 校验表单
        this.$refs.ruleForm.validate((e) => {
          if (e) {
            this.handleSubmitApi(val)
          }
        })
      } else {
        //保存表单
        this.handleSubmitApi(val)
      }
    },
    /**
     * 提交表单
     */
    handleSubmitApi(val) {
      let that = this
      let api = [update, create][that.editModel - 1] // 根据操作切换url地址
      that.loading = true
      let formData = that.$clone(that.form)
      let princi = formData.princi ? formData.princi.key.split('/') : []
      let form = {
        ...formData,
        deptPrincipalId: formData.deptPrincipal.key,
        principal: princi[0] ? princi[0] : '', // 人员ID
        principalJobsId: princi[1] ? princi[1] : '', //岗位ID
        principalJobs: formData.princi ? formData.princi.label : '',
        overseeStatus: val == '2' ? 'NO_FEEDBACK' : 'DRAFT' //结果已提交未反馈：NO_FEEDBACK； 待提交：DRAFT
      }
      api(form)
        .then(() => {
          that.loading = false
          if (val == '2') {
            that.$message.success('提交成功！')
          } else {
            that.$message.success('保存成功！')
          }
          that.$multiTab.close()
        })
        .catch(() => {
          that.loading = false
        })
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .ant-form-item {
  .ant-form-item-label {
    height: 28px;
    width: 200px;
    line-height: 22px;
    padding: 6px 4px 0 0;
    text-align: right;
    white-space: pre-wrap;
    overflow: visible;
  }
  .ant-form-item-control-wrapper {
    width: calc(100% - 200px);
  }
}
.file_prompt {
  color: #999;
}
</style>
